'''
KNN
'''

import scipy.io as scio
import datetime
import numpy as np
from sklearn import tree, neighbors
from sklearn import metrics


# 读取mat文件
def readMat(matPath):
    return scio.loadmat(matPath)


# 加载数据集
matPath = 'dataSet20180402.mat'
dataSet = readMat(matPath)
print('数据集读取完成')

# 读取数据集
test = np.array(dataSet['test'])
testX = np.array(dataSet['testX'])
testY = np.array(dataSet['testY']).T[0]
train = np.array(dataSet['train'])
trainX = np.array(dataSet['trainX'])
trainY = np.array(dataSet['trainY']).T[0]
print('数据集读取完成')

neighborsSize = [1, 5, 10, 20, 50, 100]
paraResult = []
for nei in neighborsSize:
    startTime = datetime.datetime.now()
    print('neighborsSize:' + str(nei))
    clf = neighbors.KNeighborsClassifier(n_neighbors=nei, weights='distance', n_jobs=2)
    clf.fit(trainX, trainY)
    score = clf.score(trainX, trainY)
    print('计算精度：' + str(score))
    score = clf.score(testX, testY)
    print('测试精度：' + str(score))
    predictY = clf.predict(testX)
    print('召回率：' + str(metrics.recall_score(testY, predictY)))
    confusion_matrix = metrics.confusion_matrix(testY, predictY)
    print("混淆矩阵：\n %s" % confusion_matrix)
    TP = confusion_matrix[1][1]
    TN = confusion_matrix[0][0]
    FN = confusion_matrix[1][0]
    FP = confusion_matrix[0][1]
    accuracy = (TP + TN) / (TP + TN + FN + FP)
    Specitivity = TN / (TN + FP)
    Sensitivity = TP / (TP + FN)
    print("准确度： %s" % accuracy)
    print("特异度： %s" % Specitivity)
    print("敏感度： %s" % Sensitivity)

    paraResultItem = {}
    paraResultItem['neighborsSize'] = nei
    paraResult.append(paraResultItem)
    endTime = datetime.datetime.now()
    print(endTime - startTime)
print('KNN结束')
